package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ArticleListContract
import fm.dongman.animefm.view.activity.WebViewActivity
import fm.dongman.animefm.view.adapter.CosPlayDetailsAdapter
import fm.dongman.animefm.view.adapter.UsedAdapter
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ArticleModel
import fm.dongman.modellib.source.ArticleListRepository
import fm.dongman.presenterlib.presenter.ArticleListPresenter
import kotlinx.android.synthetic.main.fragment_article_list.*
import kotlinx.android.synthetic.main.item_article_list.view.*
import org.jetbrains.anko.onClick

/**
 * 发现》漫圈》分类点击显示详情页
 * Created by shize on 2017/9/28.
 */
class ArticleListFragment : BaseFragment(), ArticleListContract.IArticleListView {
    private var mPresenter: ArticleListContract.IArticleListPresenter? = null // 数据控制器
    private var mFlagType: String = TYPE_SEARCH // 文章类型
    private var mFlagKey: String? = null // 关键字

    private lateinit var mScrollListener: LoadMoreRecyclerOnScrollListener // 滑动监听器

    private lateinit var mArticleListAdapter: ArticleListAdapter // 文章列表适配器
    private val mArticleList: ArrayList<IModel.IArticleModel> = ArrayList() // 文章数据集合

    private lateinit var mFooterView: View // 列表底部 View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_article_list, container, false)
        ArticleListPresenter(this, Injection.provideArticleListRepository())
        return view
    }

    override fun setNewParam(key: String) {
        mFlagKey = key
        requestListData(1)
    }

    override fun requestListData(page: Int) {
        mPresenter?.getArticles(page, mFlagType, mFlagKey)
        mScrollListener.clearPage()
        mArticleListAdapter.addFooterView(mFooterView)
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun initData() {
        if (arguments != null) {
            mFlagType = arguments.getString(FLAG_TYPE)
            if (mFlagKey == null)
                mFlagKey = arguments.getString(FLAG_ID)
        }
    }

    override fun bindData() {
        bindToolbar()
        bindArticleList()
    }

    /**
     * 绑定 Toolbar
     */
    private fun bindToolbar() {
        `mArticleListToolbar`.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        `mArticleListToolbar`.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
        //判断显示标题
        when (mFlagType) {
            TYPE_COSPLAY ->
                `mArticleListToolbar`.title = getString(R.string.str_article_cosplay)
            TYPE_CARD ->
                `mArticleListToolbar`.title = getString(R.string.str_article_comment)
            TYPE_INVENTORY ->
                `mArticleListToolbar`.title = getString(R.string.str_article_inventory)
            TYPE_COMIC ->
                `mArticleListToolbar`.title = getString(R.string.str_article_comic)
            TYPE_INFO ->
                `mArticleListToolbar`.title = getString(R.string.str_article_information)
            TYPE_SEARCH ->
                `mArticleListToolbar`.visibility = View.GONE
            else -> Toast.makeText(activity, getString(R.string.str_type_error), Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 绑定 RecyclerView
     */
    @SuppressLint("InflateParams")
    private fun bindArticleList() {
        mFooterView = LayoutInflater.from(activity).inflate(R.layout.layout_loading, null)
        mArticleListAdapter = ArticleListAdapter(activity, mArticleList)
        mArticleListRecycler.adapter = mArticleListAdapter
        mArticleListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mArticleListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                mPresenter?.getArticles(currentPage, mFlagType, mFlagKey)
            }
        }
        mArticleListRecycler.addOnScrollListener(mScrollListener)
        if (mFlagType == TYPE_SEARCH)
            requestListData(1)
    }

    override fun setPresenter(presenter: ArticleListContract.IArticleListPresenter) {
        mPresenter = presenter
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError("动漫详情" + getString(R.string.str_refresh_failed))
        onStateChanged(MultiStateLayout.EMPTY)
    }

    override fun showArticles(articles: List<IModel.IArticleModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mArticleList.clear()
        mArticleList.addAll(articles)
        mArticleListAdapter.notifyDataSetChanged()
        if (articles.size < 10) {
            // 加载完毕
            mArticleListAdapter.removeFooterView()
        }
    }

    override fun showMoreArticles(articles: List<IModel.IArticleModel>) {
        mArticleList.addAll(articles)
        mArticleListAdapter.notifyDataSetChanged()
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    /**
     * 切换状态
     */
    private fun onStateChanged(state: Int) {
        mArticleListMultiState?.changeState(state)
    }

    companion object {
        private val FLAG_ID = "fm.dongman.animefm.articleList.flagId" // ID key
        private val FLAG_TYPE = "fm.dongman.animefm.articleList.flagType" // 类型 key

        val TYPE_COSPLAY = ArticleListRepository.TYPE_COSPLAY          // CosPlay
        val TYPE_CARD = ArticleListRepository.TYPE_CARD                // 漫萜
        val TYPE_INVENTORY = ArticleListRepository.TYPE_INVENTORY      // 盘点
        val TYPE_COMIC = ArticleListRepository.TYPE_COMIC              // 漫画
        val TYPE_INFO = ArticleListRepository.TYPE_INFO                // 情报
        val TYPE_SEARCH = ArticleListContract.IArticleListPresenter.TYPE_SEARCH  // 搜索

        /**
         * 获取fragment 的实例

         * @param flagId 标记
         * *
         * @return DetailsArticleFragment实例
         */
        fun getInstance(flagType: String, flagId: String?): ArticleListFragment {
            val fragment = ArticleListFragment()
            val args = Bundle()
            args.putString(FLAG_ID, flagId)
            args.putString(FLAG_TYPE, flagType)
            fragment.arguments = args
            return fragment
        }
    }

    /**
     * 文章列表适配器
     */
    private class ArticleListAdapter constructor(private val mContext: Context, private val mData: List<IModel.IArticleModel>)
        : UsedAdapter<ArticleListAdapter.ArticleListViewHolder>() {
        @SuppressLint("InflateParams")
        override fun onCreateVH(): ArticleListViewHolder =
                ArticleListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_article_list, null))

        override fun onBindVH(holder: ArticleListViewHolder, position: Int) {
            val model = mData[position] as ArticleModel
            Glide.with(mContext)
                    .load(model.imgUrl)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 2)
                    ).into(holder.mCover)
            holder.mTitle.text = model.title
            holder.mSummary.text = model.summary
            holder.mUser.text = model.userSource
            holder.mCreateTime.text = model.createTime
            holder.itemView.onClick {
                mContext.startActivity(WebViewActivity.getIntent(mContext, model.articleURL))
            }
        }

        override fun getDataTotal(): Int = mData.size

        private class ArticleListViewHolder(itemView: View) : UsedViewHolder(itemView) {
            val mCover = itemView.mIvArticleListCover!!
            val mTitle = itemView.mTvArticleListTitle!!
            val mSummary = itemView.mTvArticleListSummary!!
            val mUser = itemView.mTvArticleListUser!!
            val mCreateTime = itemView.mTvArticleListCreateTime!!
        }
    }
}
